package com.fluxtool.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fluxtool.entity.UserVo;

@Controller
@RequestMapping
public class LoginController {

	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@PostMapping("/login")
	public String login(String loginName, String password, HttpServletRequest request){
		HttpSession ssession = request.getSession();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			UserVo user = (UserVo) subject.getPrincipal();
			ssession.setAttribute("user", user);
			return "ips";
		} catch (Exception e) {
			e.printStackTrace();
			return "login";
		}
	}
	
	@GetMapping("/login")
	public String loginView(){
		return "login";
	}
	
	@GetMapping("/logout")
	public String loginOut(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	
}
